package org.deng.learn.webflux.advice;

import org.deng.learn.webflux.exception.ValidException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.support.WebExchangeBindException;

/**
 * @author 邓力宾
 * @date 2020/12/21 10:30
 * @desc 参数校验异常 处理切面
 */
@ControllerAdvice
public class ValidAdvice {

    @ExceptionHandler(WebExchangeBindException.class)
    public ResponseEntity<String> handleException(WebExchangeBindException e){
        return new ResponseEntity<>(toStr(e), HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(ValidException.class)
    public ResponseEntity<String> handleValidException(ValidException e){
        return new ResponseEntity<>(e.getFieldName()+"：错误的值"+e.getFieldValue(), HttpStatus.BAD_REQUEST);
    }
    private String toStr(WebExchangeBindException exe) {
        return exe.getFieldErrors()
                .stream()
                .map(e->e.getField() +":"+e.getDefaultMessage())
                .reduce("", (s1, s2) -> s1 +"\n"+ s2 );
    }
}
